<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.name" placeholder="部门名称"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="query">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="sn" label="部门编号" width="120" sortable>
			</el-table-column>
      <el-table-column prop="name" label="部门名称" width="150" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="150" sortable>
        <template slot-scope="scope">
          <span v-if="scope.row.state == 0" style="color: #42d885">
            正常
          </span>
          <span v-else style="color:red;">
            禁用
          </span>
        </template>
      </el-table-column>
			<el-table-column prop="manager.username" label="部门管理员" width="180"  sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="上级部门" width="180" sortable>
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger"
                 @click="batchRemove"
                 :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :page-size="pageSize"
                     :current-page="currentPage"
                     :total="total"
                     style="float:right;">
			</el-pagination>
		</el-col>


		<!--编辑界面
		id: null,
    sn: '',
		name: '',
    dirPath:'',
    state: 0,
    manager:'',
    parent:'',
		-->
		<el-dialog :title="title"  :visible.sync="editFormVisible" :close-on-click-modal="false" @close="closeFresh">
			<el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="编号" prop="sn">
          <el-input v-model="editForm.sn" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="姓名" prop="name">
					<el-input v-model="editForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="editForm.state">
						<el-radio class="radio" :label="0">正常</el-radio>
						<el-radio class="radio" :label="-1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
        <el-form-item label="管理员" prop="manager">
          <el-select v-model="editForm.manager" value-key="id" placeholder="请选择">
            <!--
            v-for="item in employees" 遍历数据
            :key="item.id"唯一标识
            :label="item.usrname"//下拉框中显示的内容
            :value="item" 你要上传的数据，如果要上传一个对象 要在上面添加一个value-key
            -->
            <el-option
                v-for="item in employees"
                :key="item.id"
                :label="item.username"
                :value="item">
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门" prop="parent">
          <span class="demonstration"></span>
              <!--
               :options="deptTree"模型层数据
              :props="{
                checkStrictly: true,
                value:'id', //将parent的id传回给服务器
                label:'name',   //页面显示的内容
                     -->
          <el-cascader
              v-model="editForm.parent"
              :options="deptTree"
              :props="{
                checkStrictly: true,
                value:'id',
                label:'name',
              }"
              clearable></el-cascader>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="editFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
					name: ''
				},
				departments: [],//部门数据
        employees:[],//员工数据
        deptTree:[],//部门树
				total: 0,//总条数
				currentPage: 1,//当前页
        pageSize:5,//显示的条数
				listLoading: false,
				sels: [],//列表选中列
        //编辑
				editFormVisible: false,//编辑界面是否显示
        title:'',
				editLoading: false,
				editFormRules: {//校验规则
					name: [
						{ required: true, message: '请输入部门', trigger: 'blur' }
					]
				},
				//编辑界面数据
				editForm: {
					id: null,
          sn: '',
					name: '',
          dirPath:'',
          state: 0,
          manager:null,
          parent:null,
				},
			}
		},
		methods: {
      closeFresh(){
        this.$refs['editForm'].resetFields();
      },

			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDepartments();
			},
      query(){
			  //定位到第一页
        this.currentPage=1;
        this.getDepartments();
      },

			//获取用户列表
			getDepartments() {
        //封装参数
				let para = {
          currentPage: this.currentPage,
          pageSize:this.pageSize,
          search: this.filters.name
				};
				//加载忙等框
				this.listLoading = true;
        //发送axios
        this.$http.post("/dept",para)
        .then(result=>{//发送请求成功
          //关闭忙等框
          this.listLoading = false;
          //console.log(result);
          result=result.data;
          this.departments=result.rows;
          this.total=result.total;
        })
        .catch(result=>{//发送请求失败
          this.$message({
            message: '请求失败',
            type: 'error'
          });
        })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {//确定删除
					this.listLoading = true;
					//NProgress.start();
					//发送请求
          this.$http.delete("/dept/"+row.id)
          .then(result=>{//请求成功
            this.listLoading = false;
            //console.log(result)
            result=result.data;
              if(result.success){
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
                this.getDepartments();
                this.getDeptTree();
              }else {
                result.msg
              }
          })
          .catch(result=>{//请求失败
            this.listLoading = false;
            this.$message({
              message: '系统异常',
              type: 'error'
            });
          })
				}).catch(() => {//取消删除

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
			  //打开模态框
				this.editFormVisible = true;
				this.title="编辑";
				this.editForm = Object.assign({}, row);
				//回显上级部门
        this.getDeptTree();
        if(this.editForm.dirPath){
          let arr=this.editForm.dirPath.split("/");
          let arrPath=[];
          for(let i=1;i<=arr.length-2;i++){
            console.log(arr[i]);
              arrPath.push(parseInt(arr[i]));
          }
          this.editForm.parent=arrPath;
        }
			},
			//显示新增界面
			handleAdd: function () {
				this.editFormVisible = true;
        this.title="新增";
				this.editForm = {
          id: null,
          sn: '',
          name: '',
          dirPath:'',
          state: 0,
          manager:null,
          parent:null,
				};
				this.getDeptTree();
			},

			//编辑
			editSubmit: function () {
			  //获取ref中的名叫editForm的对象
				this.$refs.editForm.validate((valid) => {
				  //validate效验规则
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
						  //按钮忙等框
							this.editLoading = true;
							//NProgress.start();
              //克隆获取的表单数据
							let para = Object.assign({}, this.editForm);
							//对parent做一个处理
              if(para.parent){
                //将parent数组转换为对象 para.parent.length-1相当于取得下标
                para.parent={"id":para.parent[para.parent.length-1]}
              }

							//发送请求
              this.$http.put("/dept",para)
                  .then(result=>{//请求成功
                    //关闭按钮忙等框
                    this.editLoading = false;
                    //关闭模态框
                    this.editFormVisible = false;
                    result=result.data;
                    if(result.success){
                      this.$message({
                        message: '操作成功',
                        type: 'success'
                      });
                    }
                    //刷新页面
                    this.query();
                  })
                  .catch(result=>{//请求失败
                    //关闭按钮忙等框
                    this.editLoading = false;
                    this.$message({
                      message: '系统异常',
                      type: 'error'
                    });
                  })
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
			  //获取当前项的id
				var ids = this.sels.map(item => item.id);
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {//确定按钮
				  //开启忙等框
					this.listLoading = true;
					//NProgress.start();
					this.$http.patch("/dept",ids)
          .then(result=>{//请求成功
            //关闭忙等框
            this.listLoading = false;
            result=result.data;
            if(result.success){
              this.$message({
                message: '删除成功',
                type: 'success'
              });
            }
            //刷新页面
            this.query();
            this.getDeptTree();
          })
					.catch(result=>{//请求失败
            this.$message({
              message: '系统异常',
              type: 'error'
            });
          })
				}).catch(() => {//取消

				});
			},
      //查询员工数据
      getEmployees(){
			  this.$http.get("/employee")
        .then(result=>{
          result=result.data;
          //console.log(result);
          this.employees=result;
        })
      },
      //查询部门树
      getDeptTree(){
        this.$http.get("/dept/tree")
            .then(result=>{
              result=result.data;
              this.deptTree=result;
             // console.log(result);
            })
      }
		},
		mounted() {
			this.getDepartments();
			this.getEmployees();
		}
	}

</script>

<style scoped>

</style>